var mapPanel, tree;
var map, imgPanelLegend, resizePanel;
var land_covers;
var degradations;
var httpRequest = null;
var popup;
var lonLat;
var processing;
Ext
		.onReady(function() {
			processing = false;
			// console.log('Begin');
			// create a map panel with some layers that we will show in our
			// layer tree
			// below.
			OpenLayers.DOTS_PER_INCH = 90.71428571428572;
			OpenLayers.Util.onImageLoadErrorColor = 'transparent';
			resizePanel = function() {
				var height = Ext.getBody().getViewSize().height;
				height = height - 402;
				if (imgPanelLegend.isVisible()) {
					height = height - imgPanelLegend.height;

				}
				tree.setSize(260, height);
			};
			// imgPanelLegend = new Ext.Panel(
			// {
			// border : true,
			// region : "center",
			// height : 200,
			// id : "imgPanelLegend",
			// autoScroll : true,
			// bodyStyle
			// :'background-image:url("lc.png");position:center;background-repeat:no-repeat;background-size:123px
			// 199px;',
			// scroll : true,
			// containerScroll : true,
			// ddScroll : true,
			// visible : false
			// });

			imgPanelLegend = new Ext.Panel(
					{
						border : true,
						region : "center",
						height : 200,
						autoScroll : true,
						bodyStyle : 'background-image: url("lc.png");background-position:0px 0px;background-repeat:no-repeat;background-size: 123px 199px;',
						autoScroll : true,
						scroll : true,
						containerScroll : true,
						ddScroll : true,
						tbar : toolbarDocuments
					});
			// console.log('imgPanelLegend console');
			var mapOptions = {
				resolutions : [ 1222.9924523925781, 611.4962261962891,
						305.74811309814453, 152.87405654907226,
						76.43702827453613, 38.218514137268066,
						19.109257068634033, 9.554628534317017 /*
																 * ,
																 * 4.777314267158508,
																 * 2.388657133579254,
																 * 1.194328566789627,
																 * 0.5971642833948135,
																 * 0.29858214169740677,
																 * 0.14929107084870338,
																 * 0.07464553542435169
																 */],
				projection : new OpenLayers.Projection('EPSG:900913'),
				displayProjection : new OpenLayers.Projection('EPSG:4326'),
				maxExtent : new OpenLayers.Bounds(-2.003750834E7,
						-2.003750834E7, 2.003750834E7, 2.003750834E7),
				units : "meters",
				controls : []
			};
			map = new OpenLayers.Map('map', mapOptions);
			map.addControl(new OpenLayers.Control.PanZoomBar({
				position : new OpenLayers.Pixel(2, 15)
			}));

			map.addControl(new OpenLayers.Control.Navigation());
			map.addControl(new OpenLayers.Control.Scale($('scale')));
			map.addControl(new OpenLayers.Control.Attribution());
			map.addControl(new OpenLayers.Control.MousePosition({
				element : $('location')
			}));

			map.events.register('click', map, function(e) {
				if (processing)
					return;

				var opx = map.getLonLatFromPixel(e.xy);
				if (!httpRequest) {
					httpRequest = CreateHTTPRequestObject(); // defined
					// in
					// ajax.js
				}

				if (httpRequest) {
					processing = true;
					lonLat = opx;
					// The requested file must be in the same
					// domain that the page is served from.
					var url = "get_degradation_type.jsp";
					url += "?p_x=" + opx.lon + "&p_y=" + opx.lat;
					httpRequest.open("GET", url, true); // async
					httpRequest.onreadystatechange = OnStateChange;
					httpRequest.send(null);
				}
			});

			function showPopup(type) {
				if (type == ("-1")) {
					try {
						map.removePopup(popup);
						popup.destroy();
					} catch (err) {
						// Handle errors here
					}
					return;
				}

				try {
					map.removePopup(popup);
					popup.destroy();
				} catch (err) {
					// Handle errors here
				}

				if (!lonLat)
					return;
				if (type == ("-1"))
					return;
				var text = "Unknown";
				if (type == ("1"))
					text = "Soil degradation caused by mudflows and landslides";
				if (type == ("2"))
					text = "Soil degradation caused by flooding";
				if (type == ("3"))
					text = "Secondary bogging";
				if (type == ("4"))
					text = "Rockfalls and rock avalanches";
				if (type == ("5"))
					text = "Landslide";
				if (type == ("6"))
					text = "Areas inundated by flooding";
				if (type == ("7"))
					text = "Mudflows with accompanying ravine erosion";
				if (type == ("8"))
					text = "Soil salinization";
				if (type == ("9"))
					text = "Wind erosion";
				if (type == ("11"))
					text = "Bogging";
				if (type == ("13"))
					text = "Erosion";
				if (type == ("14"))
					text = "Chemical pollution of soils";
				var htmlT = '<img src="dg_imgs/' + type + '.png" alt="' + text
						+ '">' + text;
				popup = new OpenLayers.Popup.FramedCloud("popup", lonLat, null,
						htmlT, null, true);
				map.addPopup(popup);

			}

			function OnStateChange() {
				if (httpRequest.readyState == 0 || httpRequest.readyState == 4) {
					if (IsRequestSuccessful(httpRequest)) { // defined in
						processing = false;
						showPopup(httpRequest.responseText.trim());
					} else {
						processing = false;
						showPopup("-1");
					}
				}
			}

			var wmsurl = "http://31.146.171.35:8082/geoserver/cenn/wms";
			var gwcurl = "http://31.146.171.35:8082/geoserver/gwc/service/wms";
			var googleOp = 0.5;
			// gwcurl = wmsurl;
			var borders = new OpenLayers.Layer.WMS("Borders", gwcurl, {
				sphericalMercator : true,
				layers : "OnlyBorders",
				transparent : true,
				format : "image/png"
			},

			{
				isBaseLayer : true,
				visibility : true
			}

			);

			land_covers = new OpenLayers.Layer.WMS("Land covers", gwcurl, {
				sphericalMercator : true,
				layers : "Land_covers",
				transparent : true,
				format : "image/png"
			},
			// {
			// 'attribution' : "<img src='LandCover.png'>"
			// },
			{
				isBaseLayer : false,
				visibility : true
			});
			// console.log('land_covers console');
			imgPanelLegend.setVisible(land_covers.getVisibility());

			degradations = new OpenLayers.Layer.WMS("Degradations", gwcurl, {
				sphericalMercator : true,
				layers : "cenn:soil_degradation",
				transparent : true,
				format : "image/png"
			}, {
				isBaseLayer : false,
				visibility : true
			});
			//
			/*
			 * var contours = new OpenLayers.Layer.WMS( "Contours", gwcurl, {
			 * sphericalMercator : true, layers : "cenn:contours", transparent :
			 * true, format : "image/png" }, { isBaseLayer : false, visibility :
			 * false });
			 * 
			 * var roads = new OpenLayers.Layer.WMS( "Roads", gwcurl, {
			 * sphericalMercator : true, layers : "cenn:roads", transparent :
			 * true, format : "image/png" }, { isBaseLayer : false, visibility :
			 * false });
			 */

			var region_labels = new OpenLayers.Layer.WMS("Region labels",
					gwcurl, {
						sphericalMercator : true,
						layers : "cenn:region_labels",
						transparent : true,
						format : "image/png"
					}, {
						isBaseLayer : false,
						visibility : false
					});

			/*
			 * var elevation_points = new OpenLayers.Layer.WMS( "Elevation
			 * points", gwcurl, { sphericalMercator : true, layers :
			 * "cenn:elevation_points", transparent : true, format : "image/png" }, {
			 * isBaseLayer : false, visibility : false });
			 * 
			 * 
			 * var railway = new OpenLayers.Layer.WMS( "Railway", gwcurl, {
			 * sphericalMercator : true, layers : "RailwayGroup", transparent :
			 * true, format : "image/png" }, { isBaseLayer : false, visibility :
			 * false }); var settlements = new OpenLayers.Layer.WMS(
			 * "Settlements", gwcurl, { sphericalMercator : true, layers :
			 * "cenn:settlements", transparent : true, format : "image/png" }, {
			 * isBaseLayer : false, visibility : false });
			 */

			var water = new OpenLayers.Layer.WMS("Water", gwcurl, {
				sphericalMercator : true,
				layers : "WaterGroup",
				transparent : true,
				format : "image/png"
			}, {
				isBaseLayer : false,
				visibility : false
			});
			var empty = new OpenLayers.Layer.WMS("Empty", wmsurl, {
				sphericalMercator : true,
				layers : "cenn:emptytbl",
				transparent : true,
				format : "image/png"
			}, {
				isBaseLayer : false,
				visibility : true,
				googlel : true,
				op : 1.0
			});
			/*
			 * var Old2000000 = new OpenLayers.Layer.WMS( "Old 200 000", gwcurl, {
			 * sphericalMercator : true, layers : "Old2000000", transparent :
			 * true, format : "image/png" }, { isBaseLayer : false, visibility :
			 * false });
			 */
			var gphy = new OpenLayers.Layer.Google("Google Physical", {

				type : G_PHYSICAL_MAP,
				isBaseLayer : false,
				sphericalMercator : true,
				visibility : false,
				googlel : true,
				op : googleOp
			});

			var gmap = new OpenLayers.Layer.Google("Google Streets", // the
			// default
			{
				isBaseLayer : false,
				sphericalMercator : true,
				visibility : false,
				googlel : true
			});
			var ghyb = new OpenLayers.Layer.Google("Google Hybrid", {
				type : G_HYBRID_MAP,
				isBaseLayer : false,
				sphericalMercator : true,
				visibility : false,
				googlel : true,
				op : googleOp
			});
			var gsat = new OpenLayers.Layer.Google("Google Satellite", {
				type : G_SATELLITE_MAP,
				isBaseLayer : false,
				sphericalMercator : true,
				visibility : false,
				googlel : true,
				op : googleOp
			});

			map.addLayers([ borders, gphy, gmap, ghyb, gsat, empty,
					land_covers, degradations, water, region_labels ]);

			var countryStore = new Ext.data.SimpleStore(
					{
						fields : [ 'alpha2code', 'name', 'borders' ],
						data : [
								[ "1", "Georgia",
										"4453727.39241658;5020264.85210017;5202438.90493883;5401644.7976862" ],
								[ "2", "Azerbaijan",
										"4982914.61055814;4635186.82134015;5608200.10256177;5148033.98684673" ],
								[ "3", "Armenia",
										"4836641.36819752;4698891.20654096;5191180.79042891;5056698.08657392" ] ]
					});
			var regionStore = new Ext.data.SimpleStore({
				url : 'region_data.jsp',
				fields : [ 'name', 'value', 'countryid' ]
			});
			var subregionStore = new Ext.data.SimpleStore({
				url : 'region_data.jsp',
				fields : [ 'name', 'value', 'countryid' ]
			});

			function gotoBounds(bounds) {
				var boxX = bounds.split(";");
				var bbox = new OpenLayers.Bounds(boxX[0], boxX[1], boxX[2],
						boxX[3]);
				map.zoomToExtent(bbox);
				// normally zoom is auto, but for some reason it zooms to 0...
				// manual zoom looks like a correct workaround
				map.zoomTo(map.getZoomForExtent(bbox));
			}

			var subregionCombo = new Ext.form.ComboBox({
				id : 'subregionCombo',
				fieldLabel : 'Subregion',
				emptyText : 'Loading...',
				store : subregionStore,
				displayField : 'name',
				valueField : 'value',
				selectOnFocus : true,
				mode : 'local',
				typeAhead : true,
				editable : false,
				triggerAction : 'all',
				selectOnFocus : true,
				width : 250,
				listeners : {
					select : {
						fn : function(combo, value) {
							gotoBounds(this.value);
						}
					}
				}

			});

			var regionCombo = new Ext.form.ComboBox({
				id : 'regionCombo',
				fieldLabel : 'Region',
				emptyText : 'Loading...',
				store : regionStore,
				displayField : 'name',
				valueField : 'value',
				selectOnFocus : true,
				mode : 'local',
				typeAhead : true,
				editable : false,
				triggerAction : 'all',
				selectOnFocus : true,
				width : 250,
				listeners : {
					select : {
						fn : function(combo, record, value) {
							gotoBounds(this.value);
							subregionCombo.clearValue();
							var country_id = record.get("countryid");
							var region_name = record.get("name");
							subregionStore.load({
								params : {
									country_id : country_id,
									region : region_name
								}
							});
						}
					}
				}

			});
			// var treeToolBarItems = [];
			var countryCombo = new Ext.form.ComboBox({
				id : 'countryCmb',
				fieldLabel : 'Country',
				hiddenName : 'country_id',
				emptyText : 'Select a country...',
				store : countryStore,
				displayField : 'name',
				valueField : 'alpha2code',
				selectOnFocus : true,
				mode : 'local',
				typeAhead : true,
				editable : false,
				selectOnFocus : true,
				triggerAction : 'all',

				listeners : {
					select : {
						fn : function(combo, record, index) {
							gotoBounds(record.get("borders"));
							// alert();
							regionCombo.clearValue();
							regionStore.load({
								params : {
									country_id : this.value
								}
							});
						}
					}
				}
			});
			var toolbarItems = [];

			// ZoomToMaxExtent control, a "button" control
			regionStore.load({
				params : {
					country_id : '1'
				}
			});
			toolbarItems.push("Country:");
			toolbarItems.push(countryCombo);

			toolbarItems.push("&nbsp;&nbsp;&nbsp;Region:");
			toolbarItems.push(regionCombo);
			toolbarItems.push("&nbsp;&nbsp;&nbsp;Subregion:");
			toolbarItems.push(subregionCombo);
			// console.log('mapPanel pre console');
			mapPanel = new GeoExt.MapPanel({
				border : true,
				region : "center",
				map : map,
				center : [ 5057912.814586121, 5030783.655851294 ],
				zoom : 5,
				tbar : toolbarItems,
				tbarStyle : 'color:red;font-size:20px'
			// , layers : [ gphy,
			// hillshades,contours,roads,elevation_points,borders ]
			});
			// console.log('mapPanel console');
			// map.setLayerIndex(borders, 1);
			// create our own layer node UI class, using the
			// TreeNodeUIEventMixin
			var LayerNodeUI = Ext.extend(GeoExt.tree.LayerNodeUI,
					new GeoExt.tree.TreeNodeUIEventMixin());

			// using OpenLayers.Format.JSON to create a nice formatted string of
			// the
			// configuration for editing it in the UI

			// var registerRadio = function(node) {
			// alert(node);
			// if (!node.hasListener("radiochange")) {
			// node.on("radiochange", );
			// }
			// }

			var googleList = new GeoExt.tree.LayerContainer({
				text : 'Google Layers',
				layerStore : mapPanel.layers,
				leaf : false,
				expanded : true,
				loader : {
					filter : function(record) {

						var isGoogle = record.get("layer").googlel;
						return isGoogle;
					},
					baseAttrs : {
						checkedGroup : "ff",
						uiProvider : "layernodeui"
					}
				}

			});
			var layerRoot = new Ext.tree.TreeNode({
				text : "All Layers sdfsdf",
				expanded : true,
				loader : {
					baseAttrs : {
						radioGroup : "foo"
					}
				}
			});
			layerRoot.appendChild(new GeoExt.tree.BaseLayerContainer({
				text : "Main",
				map : map,
				expanded : true
			}));
			layerRoot
					.appendChild(new GeoExt.tree.OverlayLayerContainer(
							{
								text : "Additional",
								map : map,
								expanded : true,
								loader : {
									filter : function(record) {
										var layer = record.get("layer");
										// var lname = layer.name;

										// alert(lname);
										return !layer.googlel
												&& !(layer.displayInLayerSwitcher === true && layer.isBaseLayer === true);
										/*
										 * return (lname.indexOf("Google") == -1 ||
										 * lname .indexOf("Empty") == -1) &&
										 * !(layer.displayInLayerSwitcher ===
										 * true && layer.isBaseLayer === true);
										 */
									},
									createNode : function(attr) {

										// add a WMS legend to each node created
										attr.component = {
											xtype : "gx_wmslegend",
											layerRecord : mapPanel.layers
													.getByLayer(attr.layer),
											showTitle : false,
											// custom class for css positioning
											// see tree-legend.html
											cls : "legend"
										};
										var node = GeoExt.tree.LayerLoader.prototype.createNode
												.call(this, attr);

										return node;
									}
								}
							}));
			// console.log('layerRoot console');
			layerRoot.appendChild(googleList);
			// The line below is only needed for this example, because we want
			// to allow
			// interactive modifications of the tree configuration using the
			// "Show/Edit Tree Config" button. Don't use this line in your code.
			// treeConfig = new OpenLayers.Format.JSON().write(treeConfig,
			// true);

			var panelTitle = "Sustainable Land Management for Mitigating Land Degradation and Reducing Poverty in the South Caucasus Region<br>";
			panelTitle += "<table><tr><td></td></tr></table><font size=\"2\">Land Sensitivity Map of the South Caucasus Region</font>";
			// console.log('tPanel pre console');
			var tPanel = new Ext.Panel({
				border : false,
				height : 31,
				region : "north",
				title : panelTitle,
				headerStyle : "font-size:15;"
			});
			// console.log('tPanel console');
			// create the tree with the configuration from above
			var toolbarItems = [];
			toolbarItems.push('Maps');
			tree = new Ext.tree.TreePanel({
				border : true,
				region : "north",
				title : "Maps",
				// tbar:toolbarItems,
				split : false,
				collapsible : false,
				// collapseMode : "mini",
				autoScroll : true,
				scroll : true,
				containerScroll : true,
				ddScroll : true,
				plugins : [ new GeoExt.plugins.TreeNodeRadioButton({
					listeners : {
						"radiochange" : function(node) {
							alert(node.text + " is now the active layersss.");
						}
					}
				}) ],
				loader : new Ext.tree.TreeLoader({
					// applyLoader has to be set to false to not
					// interfer with loaders
					// of nodes further down the tree hierarchy
					applyLoader : false,
					uiProviders : {
						"layernodeui" : LayerNodeUI
					}
				}),
				listeners : {
					CheckChange : function(node, checked) {
						// If a parent node is unchecked, uncheck all the
						// children
						imgPanelLegend.setVisible(land_covers.getVisibility());
						if (!degradations.getVisibility())
							showPopup("-1");
						resizePanel();
						var layer = node.layer;
						if (checked && layer.googlel)
							land_covers.setOpacity(layer.op);

					}
				},

				root : layerRoot,
				rootVisible : false,
				lines : false
			});
			// console.log('tree console');
			// Ext.getCmp('navTree').el.dom.style.height = '100%';
			var documentsStore = new Ext.data.SimpleStore(
					{
						fields : [ 'name', 'value' ],
						data : [
								[ "Brief information about Project",
										"Brief information about Project.docx" ],
								[
										"Analysis of Dynamics and Trends of Land Degradation in the Regions of Target Transboundary Territory of the Rivers Khrami, Debed, Alazani and Iori Basins",
										"Analysis of Dynamics and Trends of Land Degradation in the Regions of Target Transboundary Territory of the Rivers Khrami, Debed, Alazani and Iori Basins.doc" ],
								[ "Stakeholders’ Analysis Report",
										"Stakeholder Analysis Report_100112.doc" ],
								[
										"Bilateral Alazani-Iori watershed Integrated Resource Management Plan",
										"Bilateral_Alazani-Iori_IRMP_FINAL_RU.doc" ],
								[
										"Bilateral Khrami-Debeda watershed Integrated Resource Management Plan",
										"Bilateral_Khrami-Debeda_IRMP_FINAL_RU.doc" ],
								[
										"Transboundary Watershed Sustainable Land Management (SLM) Action Plans of Khrami-Debeda and Alazani-Iori  watersheds",
										"Transboundary Watershed Sustainable Land Management (SLM) Action Plans of Khrami-Debeda and Alazani-Iori  watersheds.rar" ]

						]
					});

			var documentsCombo = new Ext.form.ComboBox(
					{
						id : 'documentsCmb',
						fieldLabel : 'Country',
						hiddenName : 'country_id',
						emptyText : 'Select a document...',
						store : documentsStore,
						triggerAction : 'all',
						displayField : 'name',
						valueField : 'value',
						selectOnFocus : true,
						mode : 'local',
						typeAhead : true,
						editable : false,
						selectOnFocus : true,
						triggerAction : 'all',
						width : 220,
						tpl : '<tpl for="."><div class="x-combo-list-item">{name}&nbsp;</div></tpl>',
						listeners : {
							select : {
								fn : function(combo, record, index) {
									var url = 'docs/'
											+ encodeURIComponent(this.value);
									window.open(url, record.get("name"));
								}
							}
						}
					});

			var toolbarDocuments = [];
			toolbarDocuments.push(documentsCombo);
			// console.log('imgPanel pre console');
			var imgPanel = new Ext.Panel(
					{
						border : true,
						region : "center",
						height : 362,
						autoScroll : true,
						title : "Download document",
						bodyStyle : 'background-image: url("logodegradation.png");background-position:0px 0px;background-repeat:no-repeat;background-size: 257px 311px;',
						autoScroll : true,
						scroll : true,
						containerScroll : true,
						ddScroll : true,
						tbar : toolbarDocuments
					});

			// console.log('imgPanel console');
			otherPanel = new Ext.Panel({
				border : false,
				region : "center",

				width : 260,
				items : [ imgPanelLegend, imgPanel ],
				listeners : {
					resize : {
						fn : function(el) {
							resizePanel();
						}
					}
				}
			});
			// console.log('imgPanel console');
			var westPanel = new Ext.Panel({
				border : false,
				region : "west",

				width : 260,
				items : [ tree, otherPanel ],
				listeners : {
					resize : {
						fn : function(el) {
							resizePanel();
						}
					}
				}
			});
			// console.log('westPanel console');
			/*
			 * var centerPanel = new Ext.Panel({ border : true, region :
			 * "center", items : [ westPanel, mapPanel ] });
			 */
			new Ext.Viewport({
				layout : "fit",
				// hideBorders : true,
				border : true,
				items : {
					layout : "border",
					deferredRender : false,
					items : [ westPanel, tPanel, mapPanel ]
				}
			});
			map.setCenter(new OpenLayers.LonLat(5032229.9730858,
					5030783.6558513), 0);
			// resizePanel();
		});
